package cn.tedu.ivos.base.file;

import cn.tedu.ivos.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/v1/file")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        System.out.println("原始文件名: " + fileName);
        fileName= UUID.randomUUID()+suffix;
        System.out.println("新文件名: " + fileName);
        System.out.println("文件后缀: " + suffix);
//        指定存放图片的根路径
        String dirPath="d:/files";
//        为了提高检索性能，我们可以设置一个以当前日期为路径的多层文件夹来储存图片
//        一般以年月日为单位来创建文件夹
        SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath=sdf.format(new Date());
        System.out.println(dirPath+datePath);
        System.out.println(dirPath+datePath+fileName);
        File dirFile=new File(dirPath+datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath=dirPath+datePath+fileName;
        // 将上传的文件转移到指定路径
        file.transferTo(new File(filePath));

        return JsonResult.ok(datePath+fileName);
    }
    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        log.debug("开始处理删除图片请求:{}",imgUrl);
        new File("d:/files"+imgUrl).delete();
        return JsonResult.ok();
    }
}
